// Array to hold callback functions
var callbacks = [];

// This function is called onload in the popup code
function getPageInfo(callback){
    try {
        // Add the callback to the queue
        callbacks.push(callback);
        // Injects the content script into the current page 
        chrome.tabs.executeScript(null, {
            file: "controller/content.js"
        });
    } 
    catch (e) {
        // do nothing
    }
};

// Perform the callback when a request is received from the content script
chrome.extension.onRequest.addListener(function(request){
    try {
        // Get the first callback in the callbacks array
        // and remove it from the array
        var callback = callbacks.shift();
        
        // Call the callback function
        callback(request);
    } 
    catch (e) {
        // do nothing
    }
});

function onClickHandler(info, tab){
    var sel = info.selectionText;
    if (sel == undefined) 
        sel = '';
    var url = chrome.extension.getURL("view/popup.html");
    switch (info.menuItemId) {
        case 2:
            localStorage.searchUrl = "http://ws.spotify.com/search/1/track?q=artist:";
			localStorage.searchType = chrome.i18n.getMessage("context_txt_search_artist");
            break;
        case 3:            
			localStorage.searchUrl = "http://ws.spotify.com/search/1/track?q=track:";
			localStorage.searchType = chrome.i18n.getMessage("context_txt_search_track");
            break;
        default:			
            localStorage.searchUrl = "http://ws.spotify.com/search/1/track?q=artist:";
			localStorage.searchType = chrome.i18n.getMessage("context_txt_search_artist");			
            break;
    }
    localStorage.contextSearch = sel;
    chrome.tabs.create({
        'url': url
    }, function(tab){
        // Tab opened.
    });
}

if (chrome.contextMenus) {
    var parent = chrome.contextMenus.create({
        "title": chrome.i18n.getMessage('context_txt_search'),
        "contexts": ["selection"]
    });
    
	chrome.contextMenus.create({
        "title": chrome.i18n.getMessage('context_txt_search_artist'),
        "contexts": ["selection"],
        "onclick": onClickHandler,
        "parentId": parent
    });
    
	chrome.contextMenus.create({
        "title": chrome.i18n.getMessage('context_txt_search_track'),
        "contexts": ["selection"],
        "onclick": onClickHandler,
        "parentId": parent
    });       
}
